package com.gdcp.controller.backend;

import com.gdcp.beans.*;
import com.gdcp.common.ResponseModel;
import com.gdcp.config.RequestHolder;
import com.gdcp.service.CategoryService;
import com.gdcp.service.ProductService;
import com.gdcp.service.ShopService;
import com.gdcp.util.FileUtil;
import com.gdcp.util.ImageDto;
import com.gdcp.util.PathUtil;
import com.gdcp.util.RandomNumberUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.gdcp.util.ImageUtil.generateThumbnail;

/**
 * @author 杨华京
 * @version 1.0
 * @description
 * @since 1.8
 */
@Controller
@RequestMapping("/render/productManager")
public class ProductController_backend {

    @Autowired
    ResponseModel responseModel;
    @Autowired
    ProductService productService;
    @Autowired
    CategoryService categoryService;
    @Autowired
    CommonCode commonCode;
    @Autowired
    ShopService shopService;

    @RequestMapping(value = "/list",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> list(int pageSize, int pageNumber, String sortName, String sortOrder){
        Map<String,Object> model=commonCode.getList(pageSize, pageNumber, sortName, sortOrder);
        User user= (User) RequestHolder.getSession("user");

        for (Role role: user.getRoles()){
            if (role.getName().equals("ROLE_ADMIN")){
                return productService.findAll(model);
            }
        }

        int shop_id=user.getShop_id();
        model.put("shop_id",shop_id);
        return productService.findPageBreakByCondition(model, shop_id);
    }

    @RequestMapping(value = "/remove",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> remove(Integer[] ids){
        if (ids==null){
            return responseModel.setModel(false,"请至少选择一条记录");
        }

        return productService.removeByPrimaryKey(ids);
    }

    @RequestMapping(value = "/add",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> add(HttpServletRequest request){
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        return insertImage("insert",request,multipartResolver);
    }

    @RequestMapping(value = "/edit",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> edit(HttpServletRequest request) {
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        return insertImage("edit",request,multipartResolver);
    }

    private Map<String,Object> insertImage(String str, HttpServletRequest request, CommonsMultipartResolver multipartResolver) {
        boolean str_boolean=str.equals("edit");
        // 若请求中存在文件流，则取出相关的文件
        try{
            if(multipartResolver.isMultipart(request)){
                //获取文件流中图片信息
                MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

                // 取出缩略图并构建ImageHolder对象
                Integer id=null;
                if (str_boolean) {
                     id = Integer.valueOf(multipartRequest.getParameter("id"));
                }

                if (multipartRequest.getParameter("stock")==null){
                    return responseModel.setModel(false,"库存不能为空");
                }

                if (multipartRequest.getParameter("status")==null){
                    return responseModel.setModel(false,"状态不能为空");
                }

                Integer shopId=null;
                User user= (User) RequestHolder.getSession("user");
                for (Role role: user.getRoles()){
                    if (role.getName().equals("ROLE_ADMIN")){
                        if (multipartRequest.getParameter("shop_id").equals("")){
                            return responseModel.setModel(false,"店铺id不能为空");
                        }
                        shopId = Integer.valueOf(multipartRequest.getParameter("shop_id"));
                        //System.out.println(shopId);
                    }
                }

                if (shopId==null){
                    shopId=user.getShop_id();
                }

                if (multipartRequest.getParameter("category_id_next")==null){
                    return responseModel.setModel(false,"分类不能为空");
                }

                Integer category_id = Integer.valueOf(multipartRequest.getParameter("category_id_next"));

                Category category=categoryService.getInformation(category_id);
                if (category==null){
                    return responseModel.setModel(false,"该分类不存在");
                }
                //System.out.println(category.getShop_id()+","+shopId);
                /*if (category.getShop_id().intValue() != shopId.intValue()){
                    return responseModel.setModel(false,"注意:"+category_id+"分类不属于id为" +
                            shopId+"店铺的,"+"它是属于id为"+category.getShop_id()+"店铺的");
                }*/

                String name = multipartRequest.getParameter("name");
                String subtitle = multipartRequest.getParameter("subtitle");
                String detail = multipartRequest.getParameter("detail");
                String price = multipartRequest.getParameter("price");

                Integer stock = Integer.valueOf(multipartRequest.getParameter("stock"));
                Integer status = Integer.valueOf(multipartRequest.getParameter("status"));
                MultipartFile mainImageFile = multipartRequest.getFile("main_image");

                MultipartFile imageLeftFile = multipartRequest.getFile("image_left");
                MultipartFile imageCenterFile = multipartRequest.getFile("image_center");
                MultipartFile imageRightFile = multipartRequest.getFile("image_right");

                ImageDto mainImage,imageLeft,imageCenter,imageRight;
                mainImage=imageLeft=imageCenter=imageRight=null;

                if (mainImageFile != null) {
                    mainImage = new ImageDto(mainImageFile.getOriginalFilename(), mainImageFile.getInputStream());
                }
                if (imageLeftFile != null) {
                    imageLeft = new ImageDto(imageLeftFile.getOriginalFilename(), imageLeftFile.getInputStream());
                }
                if (imageCenterFile != null) {
                    imageCenter = new ImageDto(imageCenterFile.getOriginalFilename(), imageCenterFile.getInputStream());
                }
                if (imageRightFile != null) {
                    imageRight = new ImageDto(imageRightFile.getOriginalFilename(), imageRightFile.getInputStream());
                }

                Product product=new Product();

                //如果不为系统分类，那么就插入parent_id系统分类
                if (category.getShop_id()!=0){
                    product.setCategory_id(category.getParent_id());
                    product.setCategory_id_next(category.getId());
                }
                //如果为系统分类，那么就直接插入id
                else{
                    product.setCategory_id(category.getId());
                    product.setCategory_id_next(category.getId());
                }
                product.setName(name);
                product.setSubtitle(subtitle);
                //product.setDetail(detail);


                product.setPrice(price);
                product.setStock(stock);
                product.setStatus(status);

                product.setShop_id(shopId);
                if (str_boolean){
                    product.setId(id);
                    Product productInfo=productService.getInformation(id);
                    detail = detail.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
                    String content = URLDecoder.decode(detail, "UTF-8");
                    // 路径=固定+随机生成
                    String relativeAddr=productInfo.getDetail();
                    // 获取存储的路径
                    String base=relativeAddr;
                    FileUtil.clearInfoForFile(base);
                    FileUtil.writeWord(content,base);
                    return productService.updateInformation(product,mainImage,imageLeft,imageCenter,imageRight);
                }

                detail = detail.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
                String content1 = URLDecoder.decode(detail, "UTF-8");
                //System.out.println(content1);
                // 路径=固定+随机生成
                String relativeAddr1= PathUtil.getProductBasePath() +'\\'+ RandomNumberUtil.getRandomOrderNo();
                // 获取存储的路径
                String base1=relativeAddr1+".txt";
                FileUtil.writeWord(content1,base1);
                product.setDetail(base1);
                return productService.insert(product,mainImage,imageLeft,imageCenter,imageRight);
            }
        }catch (Exception e){
            //System.out.println(e.toString());
            e.printStackTrace();
            return responseModel.setModel(false,"参数有问题");
        }

        return responseModel.setModel(true,"插入成功");
    }

    @PostMapping("/get/{id}")
    @ResponseBody
    public Map<String,Object> get(@PathVariable Integer id){
        Product product= productService.getInformation(id);
        /*HttpServletRequest request=RequestHolder.getRequest();
        if (product==null){
            return responseModel.setModel(false,"获取失败");
        }
        List<Category> category_three = categoryService.queryByShopId(product.getShop_id());
        request.setAttribute("categories_three",category_three);*/
        product.setDetail(FileUtil.readWord(product.getDetail()));
        return responseModel.setModel(true,product);
    }

    @PostMapping("/search")
    @ResponseBody
    public Map<String,Object> search(String searchText){
        String str = "["+searchText+"]";
        JSONArray json= JSONArray.fromObject(str);
        Map<String, Object> param=new HashMap<>();

        for(int i=0;i<json.size();i++){
            JSONObject jsonOne = json.getJSONObject(i);
            param.put("id", jsonOne.getString("id"));
            param.put("name", jsonOne.getString("username"));
            param.put("category_id", jsonOne.getString("categoryId"));
        }



        User user= (User) RequestHolder.getSession("user");
        for (Role role: user.getRoles()){
            if (role.getName().equals("ROLE_ADMIN")){
                return productService.searchInformation(param);
            }
        }

        param.put("shop_id",user.getShop_id());
        if (user.getShop_id()==0){
            return responseModel.setModel(false,"信息错误");
        }

        return productService.searchInformationByShopId(param,user.getShop_id());
    }

    @RequestMapping(value = "/getImage",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> getImage(HttpServletRequest request){
        String imgBase64 = request.getParameter("urls");
        //System.out.println(imgBase64);
        String url=generateThumbnail(imgBase64);
        if (url.equals("")){
            return responseModel.setModel(false,"返回路径为空");
        }

        return responseModel.setModel(true,url);
    }

    @RequestMapping(value = "/queryByParentId",method = RequestMethod.GET)
    public String queryByParentId(){
        HttpServletRequest request=RequestHolder.getRequest();
        //全部第三层
        User user= (User) RequestHolder.getSession("user");
        for (Role role: user.getRoles()){
            if (role.getName().equals("ROLE_ADMIN")){
                List<Category> category_three = categoryService.queryByAll();
                List<Shop> shops= shopService.queryByAll();
                request.setAttribute("categories_three",category_three);
                request.setAttribute("shops",shops);
            }
            if (role.getName().equals("ROLE_SHOP_ADMIN")){
                List<Category> category_three = categoryService.queryByShopId(user.getShop_id());
                request.setAttribute("categories_three",category_three);
            }
            if (role.getName().equals("ROLE_SHOP_USER")){
                List<Category> category_three = categoryService.queryByShopId(user.getShop_id());
                request.setAttribute("categories_three",category_three);
            }

        }
        return "admin/productManager";
    }
}
